package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.PaymentOrderMapper;
import com.intelligent.mapper.PaymentWriteOffMapper;
import com.intelligent.mapper.TUserMapper;
import com.intelligent.pojo.PaymentOrder;
import com.intelligent.pojo.PaymentWriteOff;
import com.intelligent.pojo.TUser;
import com.intelligent.service.PaymentWriteOffService;
import com.intelligent.vo.PaymentWriteOffCreateReq;
import com.intelligent.vo.PaymentWriteOffPageReq;
import com.intelligent.vo.PaymentWriteOffResp;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class PaymentWriteOffServiceImpl extends ServiceImpl<PaymentWriteOffMapper, PaymentWriteOff>
        implements PaymentWriteOffService {

    @Resource
    private PaymentOrderMapper paymentOrderMapper;
    @Resource
    private TUserMapper tUserMapper;

    @Override
    public Page<PaymentWriteOffResp> page(PaymentWriteOffPageReq req) {
        Page<PaymentWriteOff> entityPage = new Page<>(req.getPageNum(), req.getPageSize());

        LambdaQueryWrapper<PaymentWriteOff> qw = new LambdaQueryWrapper<>();
        if (req.getWriteOffNo() != null && !req.getWriteOffNo().trim().isEmpty()) {
            qw.like(PaymentWriteOff::getWriteOffNo, req.getWriteOffNo().trim());
        }

        // 通过付款单号筛选：先查付款单，再反查核销
        if (req.getPaymentOrderNo() != null && !req.getPaymentOrderNo().trim().isEmpty()) {
            LambdaQueryWrapper<PaymentOrder> pow = new LambdaQueryWrapper<>();
            pow.like(PaymentOrder::getPaymentOrderNo, req.getPaymentOrderNo().trim());
            java.util.List<PaymentOrder> orders = paymentOrderMapper.selectList(pow);
            if (orders == null || orders.isEmpty()) {
                // 无匹配付款单，返回空分页
                return new Page<>(req.getPageNum(), req.getPageSize(), 0);
            }
            java.util.List<Long> ids = orders.stream().map(PaymentOrder::getId).collect(Collectors.toList());
            qw.in(PaymentWriteOff::getPaymentOrderId, ids);
        }

        qw.orderByDesc(PaymentWriteOff::getId);
        this.page(entityPage, qw);

        // 批量补充付款单信息与用户姓名
        java.util.List<Long> poIds = entityPage.getRecords().stream().map(PaymentWriteOff::getPaymentOrderId).collect(Collectors.toList());
        Map<Long, PaymentOrder> idToOrder = poIds.isEmpty() ? java.util.Collections.emptyMap()
                : paymentOrderMapper.selectBatchIds(poIds).stream().collect(Collectors.toMap(PaymentOrder::getId, Function.identity()));

        java.util.List<Long> uIds = entityPage.getRecords().stream().map(PaymentWriteOff::getUId).collect(Collectors.toList());
        Map<Long, TUser> idToUser = uIds.isEmpty() ? java.util.Collections.emptyMap()
                : tUserMapper.selectBatchIds(uIds).stream().collect(Collectors.toMap(TUser::getUserId, Function.identity()));

        Page<PaymentWriteOffResp> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        voPage.setRecords(entityPage.getRecords().stream().map(pw -> {
            PaymentWriteOffResp r = new PaymentWriteOffResp();
            r.setId(pw.getId());
            r.setWriteOffNo(pw.getWriteOffNo());
            r.setPaymentOrderId(pw.getPaymentOrderId());
            r.setWriteOffAmount(pw.getWriteOffAmount());
            r.setWriteOffDate(pw.getWriteOffDate());
            r.setUId(pw.getUId());
            r.setCreateTime(pw.getCreateTime());

            PaymentOrder order = idToOrder.get(pw.getPaymentOrderId());
            if (order != null) {
                r.setPaymentOrderNo(order.getPaymentOrderNo());
                r.setRelatedSalesOrder(order.getRelatedSalesOrder());
            }

            TUser user = idToUser.get(pw.getUId());
            if (user != null) {
                r.setFinanceUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
            }
            return r;
        }).collect(Collectors.toList()));
        return voPage;
    }

    @Override
    public PaymentWriteOffResp detail(Long id) {
        PaymentWriteOff pw = this.getById(id);
        if (pw == null) return null;
        PaymentWriteOffResp r = new PaymentWriteOffResp();
        r.setId(pw.getId());
        r.setWriteOffNo(pw.getWriteOffNo());
        r.setPaymentOrderId(pw.getPaymentOrderId());
        r.setWriteOffAmount(pw.getWriteOffAmount());
        r.setWriteOffDate(pw.getWriteOffDate());
        r.setUId(pw.getUId());
        r.setCreateTime(pw.getCreateTime());

        PaymentOrder order = paymentOrderMapper.selectById(pw.getPaymentOrderId());
        if (order != null) {
            r.setPaymentOrderNo(order.getPaymentOrderNo());
            r.setRelatedSalesOrder(order.getRelatedSalesOrder());
        }
        TUser user = pw.getUId() == null ? null : tUserMapper.selectById(pw.getUId());
        if (user != null) {
            r.setFinanceUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
        }
        return r;
    }

    @Override
    public PaymentWriteOffResp create(PaymentWriteOffCreateReq req) {
        PaymentWriteOff po = new PaymentWriteOff();
        po.setWriteOffNo(req.getWriteOffNo());
        po.setPaymentOrderId(req.getPaymentOrderId());
        po.setWriteOffAmount(req.getWriteOffAmount());
        po.setWriteOffDate(req.getWriteOffDate());
        po.setUId(req.getUId());

        // 自动生成核销单号
        if (po.getWriteOffNo() == null || po.getWriteOffNo().trim().isEmpty()) {
            po.setWriteOffNo("FKHX" + System.currentTimeMillis());
        }
        // 默认核销时间与创建时间
        java.util.Date now = new java.util.Date();
        if (po.getWriteOffDate() == null) po.setWriteOffDate(now);
        po.setCreateTime(now);

        this.save(po);
        return detail(po.getId());
    }
}


